package com.xiangmo.travel.Aspect;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xiangmo.travel.Dto.ResultData;
import com.xiangmo.travel.Enums.CodeAndMsg;
import com.xiangmo.travel.Utils.TokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class TokenAspect {

    @Autowired
    private TokenUtil tokenUtil;

    @Around("@annotation(com.xiangmo.travel.Annotation.TokenRequired)")
    public Object checkToken(ProceedingJoinPoint pjp) throws Throwable {
        // 获取请求中的token信息
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        System.out.println("aop with token the value is:" + token);
        if (StringUtils.isBlank(token)) {
            throw new RuntimeException("缺少Authorization信息");
        }

        // 验证token是否合法
        String userId = tokenUtil.validateToken(token);
        if(userId == null){
            return new ResultData<>(CodeAndMsg.TOKEN_ERROR.getCode(),
                    CodeAndMsg.TOKEN_ERROR.getMessage(), null, null);
        }

        return pjp.proceed();
    }
}
